<template>
	<view class="wrap">
		<template v-if='logged'>
			<view class="cartGoodsList u-p-b-80" v-if="goodsList.length">
				<u-checkbox-group v-model="checkList" placement="column" @change="checkChange">
					<view class="cartGoods u-flex u-p-15" v-for="(item,index) in goodsList" :key='index'>
						<u-checkbox :checked="item.is_checked?true:false" :name='item.id' size="20" shape="square">
						</u-checkbox>
						<view class="goodsInfo u-flex u-p-10">
							<u--image @click="details(item.goods_id)" width="200rpx" height="200rpx"
								:src="item.goods.cover_url" shape="circle">
							</u--image>
							<view class="goodsBaseInfo u-flex u-row-between u-col-top u-p-10">
								<view class="priceNum" @click="details(item.goods_id)">
									<text class="title u-p-l-10 u-font-32">{{item.goods.title}}</text>
									<br>
									<text class="small">{{item.goods.description}}</text>
									<view class="u-text-right small">
										库存：<text style="color: red;">{{item.goods.stock}}</text>
									</view>
								</view>
								<view class="priceNum u-flex u-row-between">
									<text class="price u-font-34">￥{{item.goods.price}}</text>
									<u-number-box v-model='item.num' :min="1" :max="item.goods.stock" interger
										:name="item.id" @change='numChange($event,item.num)'></u-number-box>
									<u-icon name="trash" size="36" color="#e83333" @click="reMove(item.id)"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</u-checkbox-group>
				<view class="bottomFixed u-flex u-p-15">
					<view class="u-flex-3">
						<u-checkbox-group placement="column" @change="allCheckChange">
							<u-checkbox :checked="allCheck" size="20" name="all" shape="circle" label="全选"></u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="u-flex u-flex-7 u-row-around">
						<view>
							<text class="title">合计：</text>
							<text class="price">￥{{totalPrice}}</text>
						</view>
						<u-button @click='order' type="primary" shape="square" :disabled="!disabled">结算订单</u-button>
					</view>
				</view>
			</view>
			<!-- 购物车没有内容时给一个提示 -->
			<view class="" v-else>
				<u-empty text="购物车空空如也" mode="car"></u-empty>
			</view>
		</template>
		<template v-else>
			<!-- 提示无权限 -->
			<u-empty mode="permission" text="请登录后查看"></u-empty>
		</template>
	</view>
</template>

<script>
	let access_token;
	export default {
		data() {
			return {
				checkList: [],
				goodsList: [],
				logged: false, //表示是否处于登录状态
			}
		},
		onShow() {
			access_token = uni.getStorageSync('access_token');
			if (access_token) {
				this.logged = true;
			}
			//console.log(access_token);
			this.getData();
		},
		computed: {
			disabled() {
				//some
				return this.goodsList.some((goods) => {
					return goods.is_checked;
				})
			},
			totalPrice() {
				//console.log(this.goodsList);
				//filter
				return this.goodsList.filter((goods) => {
					return goods.is_checked;
				}).reduce((pre, goods) => {
					return parseInt(pre) + parseInt(goods.goods.price * goods.num);
				}, 0)
			},
			allCheck: {
				get() {
					//遍历goodsList数组，看是否所有商品均为选中状态。如果均选中，则返回true。一旦有一个没选中，则返回假。
					//js中有一个every和some方法. every：一假即假（一旦为假，则中止遍历）。some：一真即真（一旦为真，则中止遍历）。
					return this.goodsList.every((goods) => {
						//console.log(goods.is_checked);
						return goods.is_checked;
					})
				},
				set(val) {
					//val是当前allCheck的值，其值为true或false
					//console.log(val);
					let idArr = [];
					if (val) {
						//说明是全选
						//需要遍历goodsList，把所有购物车ID放入一个数组，调用checkChange方法即可。
						this.goodsList.forEach((goods) => {
							idArr.push(goods.id);
						})
					}
					/* else{
						//说明是取消全选
						//调用checkChange方法，提供一个空数组即可。
						idArr = [];
					} */
					this.checkChange(idArr);
				}
			}
		},
		methods: {
			order() {
				uni.$u.route('/pages/cart/order');
			},
			details(id) {
				uni.$u.route('/pages/goods/detail', {
					id: id
				})
			},
			async allCheckChange(e) {
				//console.log(e);
				if (e.length) {
					//说明是全选
					this.allCheck = true;
				} else {
					//说明是全不选
					this.allCheck = false;
				}
			},
			async reMove(id) {
				//console.log(id);
				const res = await uni.$u.http.delete(`/api/carts/${id}`, {}, {
					header: {
						Authorization: 'bearer ' + access_token
					}
				})
				if (res === false) {
					uni.$u.toast('更新数据库出错');
					return;
				}
				this.getData();
			},
			async numChange(e, lastNum) {
				//console.log(e,lastNum);
				const {
					value,
					name
				} = e;
				const res = await uni.$u.http.put('/api/carts/' + name, {
					num: value
				}, {
					header: {
						Authorization: 'bearer ' + access_token
					}
				})
				if (res === false) {
					uni.$u.toast('更新数据库出错');
					this.getData();
				}
			},
			async checkChange(e) {
				//console.log(e);
				//e返回的是当前选中的所有复选框name（也就是购物车ID）
				const res = await uni.$u.http.post('/api/carts/checked', {
					_method: 'PATCH',
					cart_ids: e
				}, {
					header: {
						Authorization: 'bearer ' + access_token
					}
				})
				if (res === false) {
					uni.$u.toast('更新数据库出错');
				}
				this.getData();
			},
			async getData() {
				const res = await uni.$u.http.get('/api/carts', {
					params: {
						include: 'goods'
					},
					header: {
						Authorization: 'bearer ' + access_token
					}
				})
				//console.log(res);
				this.goodsList = res.data;
				//console.log(this.checkList);
			}
		}
	}
</script>

<style lang="scss">
	.wrap {
		min-height: 80vh;

		.empty {
			height: 80vh;
		}

		.loading {
			text-align: center;
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
		}

		.title,
		.price {
			font-weight: 800;
			color: #e83333;
		}

		.cartGoodsList {
			.cartGoods {
				.goodsInfo {
					width: 100%;
					background-color: rgb(251, 250, 251);

					.goodsBaseInfo {
						width: 100%;
						height: 200rpx;
						flex-direction: column;

						.priceNum {
							width: 100%;
						}
					}
				}
			}
		}

		.bottomFixed {
			position: fixed;
			left: 0;
			right: 0;
			background-color: #fff;
		}

		/*#ifdef H5*/
		.bottomFixed {
			bottom: 90rpx;
		}

		/*#endif*/
		/*#ifdef MP-WEIXIN*/
		.bottomFixed {
			bottom: 0;
			z-index: 99999;
		}

		/*#endif*/
		/*#ifdef APP-PLUS*/
		.bottomFixed {
			bottom: 0;
			z-index: 99999;
		}

		/*#endif*/
	}
</style>
